package org.turman.buobaobook.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.turman.buobaobook.mapper.BookSourceMapper;
import org.turman.buobaobook.model.entity.Book;
import org.turman.buobaobook.mapper.BookMapper;
import org.turman.buobaobook.model.entity.BookSource;
import org.turman.buobaobook.model.request.QueryBookBean;
import org.turman.buobaobook.service.BookService;

import java.util.List;

@Service("bookService")
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private BookSourceMapper bookSourceMapper;

    @Override
    public Book selectById(Long bookId) {
        return bookMapper.selectById(bookId);
    }

    @Override
    public PageInfo<Book> selectList(QueryBookBean queryBookBean) {
        PageHelper.startPage(queryBookBean.getPageNum(), queryBookBean.getPageSize());
        List<Book> bookList = bookMapper.selectList();
        PageInfo pageInfo = new PageInfo(bookList);
        return pageInfo;
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public void insert(Book book, List<BookSource> bookSources) {
        bookMapper.insert(book);
        if (bookSources != null && bookSources.size() > 0) {
            bookSources.forEach(bookSource -> bookSource.setBookId(book.getBookId()));
            bookSourceMapper.insetBatch(bookSources);
        }
    }

    @Override
    public void update(Book book) {
        bookMapper.update(book);
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public void delete(Long bookId) {
        bookMapper.delete(bookId);
        bookSourceMapper.deleteBatch(bookId);
    }
}
